import pymysql
from warnings import filterwarnings

# 忽略mysql告警信息
filterwarnings("ignore", category=pymysql.Warning)


class MysqlDb:

    def __init__(self):
        # 简历数据连接
        self.conn = pymysql.connect(host='127.0.0.1', user="root", passwd="123456", db='api_test_demo')

        # 使用 cursor 方法获取操作游标，得到一个可以执行的sql语句，并且操作结果作为字典返回的游标
        self.cur = self.conn.cursor(cursor=pymysql.cursors.DictCursor)

    def __del__(self):
        # 关闭游标
        self.cur.close()
        # 关闭连接
        self.conn.close()

    def query(self, sql, state='all'):
        """
        查询
        :param sql:
        :param state:  默认查询全部
        :return:
        """
        self.cur.execute(sql)

        if state == "all":
            data = self.cur.fetchall()
        else:
            data = self.cur.fetchone()

        return data

    def execute(self, sql):
        """
        更新、删除、新增
        :param sql:
        :return:
        """
        try:
            #使用execute操作sql
            rows = self.cur.execute(sql)
            self.conn.commit()
            return rows
        except Exception as e:
            print('数据库操作异常 {0}'.format(e))
            # 回滚修改
            self.conn.rollback()


if __name__ == '__main__':

    mydb = MysqlDb()
    # r = mydb.query(sql="select * from `case` ")
    r = mydb.execute("insert into `case` (`app`) values('xd')")
    print(r)



#
# conn = pymysql.connect(host='127.0.0.1', user="root", passwd="123456", db='api_test_demo')
#
# # 使用 cursor 方法获取操作游标，得到一个可以执行的sql语句，并且操作结果作为字典返回的游标
# cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
#
# try:
#     # 使用execute执行sql
#     cursor.execute("select * from `case` ")
#     data = cursor.fetchone()
#     print(data)
# except Exception as e:
#     print(e)
#
# finally:
#     conn.close()
